//
//  WmcHomeNavView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/1.
//

import SnapKit
import UIKit
import YPGraphicEngine

public extension WmcButtonItemType {
    /// 顶部导航条
    enum HomeNavigation: Equatable {
        /// 菜单
        case menu

        /// 闪光灯
        case flash

        /// 意见反馈
        case feedback

        /// 画幅
        case aspectRatio
        
        /// 滤镜
        case filter

        /// 延时
        case delay

        /// 翻转
        case flip

        /// 相机设置
        case cameraSetting

        /// 占位，无实际意义
        case placeholder

        /// 自定义
        case custom(view: UIView)

        public static func == (lhs: Self, rhs: Self) -> Bool {
            return lhs.info.identifier == rhs.info.identifier
        }
    }
}

extension WmcButtonItemType.HomeNavigation {
    var info: Info {
        switch self {
        case .menu: return .init(identifier: "menu")
        case .flash: return .init(identifier: "flash")
        case .feedback: return .init(identifier: "feedback")
        case .aspectRatio: return .init(identifier: "aspectRatio")
        case .filter: return .init(identifier: "filter")
        case .delay: return .init(identifier: "delay")
        case .flip: return .init(identifier: "flip")
        case .cameraSetting: return .init(identifier: "cameraSetting")
        case .placeholder: return .init(identifier: "placeholder")
        case let .custom(view: view): return .init(identifier: "\(view.hashValue)")
        }
    }

    struct Info {
        var identifier: String
    }
}

// MARK: - [WmcHomeHeaderView]

/// 顶部菜单
class WmcHomeHeaderView: WmcNavView {
    /// 菜单
    lazy var menuBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn.CreateHomeHeaderBtn(title: "菜单",
                                                             image: "home_menu_setting".wmc_image)
        return btn
    }()

    /// 闪光灯
    lazy var flashBtn: WmcFlashBtn = {
        let btn = WmcFlashBtn.Create()
        btn.flashMode = .off
        return btn
    }()

    /// 意见反馈
    lazy var feedBackBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn.CreateHomeHeaderBtn(title: "意见反馈",
                                                             image: "home_menu_feedback".wmc_image)
        return btn
    }()

    /// 画幅
    lazy var aspectRatioBtn: WmcAspectRatioBtn = {
        let btn = WmcAspectRatioBtn.Create()
        return btn
    }()

    /// 延迟
    lazy var delayBtn: WmcDelayBtn = .Create()

    /// 翻转
    lazy var flipBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn.CreateHomeHeaderBtn(title: "翻转", image: "home_tool_flip".wmc_image)
        return btn
    }()

    /// 相机设置
    lazy var cameraSettingBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn.CreateHomeHeaderBtn(title: "相机设置", image: "home_menu_cam_setting".wmc_image)
        return btn
    }()
    
    /// 滤镜
    lazy var filterBtn: WmcTopImgBottomTextBtn = {
        let btn = WmcTopImgBottomTextBtn.CreateHomeHeaderBtn(title: "滤镜", image: "icon_image_filter_32".wmc_image)
        return btn
    }()

    lazy var leftStarkView: UIStackView = {
        let starkView = UIStackView()
        starkView.alignment = .center
        starkView.axis = .horizontal
        starkView.distribution = .equalSpacing
        starkView.spacing = 8
        return starkView
    }()

    lazy var rightStarkView: UIStackView = {
        let starkView = UIStackView()
        starkView.alignment = .center
        starkView.axis = .horizontal
        starkView.distribution = .equalSpacing
        starkView.spacing = 24
        return starkView
    }()

    lazy var invitationBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "邀请好友",
                                         image: "home_menu_invitation".wmc_image)
        btn.backgroundColor = .wmc_mainTheme
        btn.font = 12.wmc_font
        btn.contentEdge = .YP.Create(horizontal: 9, vertical: 7)
        btn.imgSize = 19.wmc_autoHor
        return btn
    }()

    lazy var centerContentView: UIView = {
        let view = UIView()
        return view
    }()

    /// 背景是否透明状态
    var isTransparent: Bool = false

    /// 功能模式
    var functionMode: WmcButtonItemType.HomeFunctionMode = .photo

    /// 视频录制状态
    var videoRecordState: WmcHomeVC.VideoRecordState = .stop

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let superHit = super.hitTest(point, with: event)
        guard bounds.contains(point) else { return superHit }
        for view in subviews {
            if view.frame.contains(point) {
                if !(superHit is UIStackView) {
                    return superHit
                }
            }
        }
        return nil
    }

    @objc
    func _touchDown() {
        YPDevice.PlayShake(.medium)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        invitationBtn.layer.cornerRadius = 32.0 / 2.0
        invitationBtn.layer.masksToBounds = true
    }

    override func makeUI() {
        if YPWmcManager.shared.isIndependentPage { // 平台独立包
            addSubview(invitationBtn)
            invitationBtn.snp.makeConstraints { make in
                make.bottom.equalTo(-6)
                make.centerX.equalToSuperview()
                make.height.equalTo(32)
                make.width.equalTo(94.wmc_autoHor)
            }

            addSubview(leftStarkView)
            leftStarkView.snp.makeConstraints { make in
                make.left.equalTo(Wmc_standardEdge.left)
                make.top.equalTo(Wmc_statusBarHeight)
                make.bottom.equalTo(-4)
                make.width.equalTo(10)
            }

            addSubview(rightStarkView)
            rightStarkView.snp.makeConstraints { make in
                make.top.equalTo(Wmc_statusBarHeight)
                make.bottom.equalToSuperview()
                make.right.equalTo(-Wmc_standardEdge.right)
            }

        } else { // 宿主包
            super.makeUI()
            titleLabel.text = "返回"

            if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
                let title = homeDelegate.navigationBackTitle(.current,
                                                             isTransparent: isTransparent,
                                                             functionMode: functionMode)
                titleLabel.text = title
            }

            addSubview(centerContentView)
            addSubview(leftStarkView)
            addSubview(rightStarkView)

            leftStarkView.snp.makeConstraints { make in
                make.left.equalTo(Wmc_standardEdge.left)
                make.top.equalTo(Wmc_statusBarHeight)
                make.bottom.equalTo(-4)
                make.width.equalTo(10)
            }

            rightStarkView.snp.makeConstraints { make in
                make.top.equalTo(Wmc_statusBarHeight)
                make.bottom.equalToSuperview()
                make.right.equalTo(-Wmc_standardEdge.right)
            }

            var centerViewWidth: CGFloat = 120
            if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
                let _viewWidth = homeDelegate.navigationCenterMenuViewWidth(.current,
                                                                            isTransparent: isTransparent,
                                                                            functionMode: functionMode)
                centerViewWidth = _viewWidth
            }
            centerContentView.snp.makeConstraints { make in
                make.top.bottom.equalTo(rightStarkView)
                make.centerX.equalToSuperview()
                make.width.equalTo(centerViewWidth)
            }

            if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate,
               let _view = homeDelegate.navigationCenterMenuView(.current,
                                                                 isTransparent: isTransparent,
                                                                 functionMode: functionMode)
            {
                centerContentView.addSubview(_view)
                _view.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
            }
        }

        reloadItems()
    }

    /// 重载按钮
    func reloadItems() {
        if isTransparent { // 透明
            // 返回
            backImageView.yp.set(tintColor: UIColor.white)
            titleLabel.textColor = .white

            menuBtn.setTintColor(.white)
            flashBtn.normalColor = .white
            flashBtn.selectColor = .white
            feedBackBtn.setTintColor(.white)

            aspectRatioBtn.setTintColor(.white)
            delayBtn.normalColor = .white
            delayBtn.setTintColor(.white)
            flipBtn.setTintColor(.white)
            cameraSettingBtn.setTintColor(.white)
            // 滤镜
            filterBtn.setTintColor(.white)
            
        } else { // 不透明
            // 返回
            backImageView.yp.set(tintColor: UIColor.wmc_grayH5_606066)
            titleLabel.textColor = .wmc_grayH5_606066

            menuBtn.setTintColor(.wmc_grayH5_606066)
            flashBtn.normalColor = .wmc_grayH5_606066
            flashBtn.selectColor = .wmc_grayH5_606066
            feedBackBtn.setTintColor(.wmc_grayH5_606066)

            aspectRatioBtn.setTintColor(.wmc_grayH5_606066)
            // 滤镜
            filterBtn.setTintColor(.wmc_grayH5_606066)
            
            delayBtn.normalColor = .wmc_grayH5_606066
            delayBtn.setTintColor(.wmc_grayH5_606066)
            flipBtn.setTintColor(.wmc_grayH5_606066)
            cameraSettingBtn.setTintColor(.wmc_grayH5_606066)
            
            
        }
        
        flashBtn.flashMode = flashBtn.flashMode // 刷新状态

        var hasFlashBtn: Bool = false
        for view in leftStarkView.arrangedSubviews {
            if view == flashBtn {
                hasFlashBtn = true
                break
            }
        }
        reloadLeftItems(hasFlash: hasFlashBtn)
        reloadRightItems()
    }

    func reloadLeftItems(hasFlash: Bool = true) {
        var defaultList: [WmcButtonItemType.HomeNavigation] = [
            .menu, .flash,
        ]
        switch functionMode {
        case .edit:
            break
        case .rebarCount:
            defaultList = [.flash]
        case .photo, .photoAndCombine:
            defaultList = [.menu, .flash]
        case .video:
            switch videoRecordState {
            case .stop:
                defaultList = [.menu, .flash]
            case .being, .pause:
                defaultList = [.placeholder, .flash]
            }
        case .custom:
            break
        }
        if !YPWmcManager.shared.isIndependentPage { // 宿主包的话
            defaultList = []
        }
        if !hasFlash { // 没有闪光灯，移除闪光灯
            defaultList = removeItem(list: defaultList, _case: .flash)
        }
        guard !defaultList.isEmpty else { return }
        let views = toItemList(defaultList)
        let viewWidth = defaultList.count * 40
        let space = (defaultList.count - 1) * 8
        let width = viewWidth + space
        leftStarkView.snp.updateConstraints { make in
            make.width.equalTo(width)
        }
        leftStarkView.yp.arrangedSubviews = views
    }

    func reloadRightItems(hasFlash: Bool = true) {
        
        var defaultList: [WmcButtonItemType.HomeNavigation] = [
            .filter, .feedback
        ]
        if !YPWmcManager.shared.isIndependentPage { // 宿主包的话
            defaultList = [.flash, .filter, .menu]
        }
        
        if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
            let _defaultList = homeDelegate.navigationRightMenuList(.current,
                                                                    isTransparent: isTransparent,
                                                                    functionMode: functionMode,
                                                                    defaultList: defaultList)
            defaultList = _defaultList
        }
        if !hasFlash { // 没有闪光灯，移除闪光灯
            defaultList = removeItem(list: defaultList, _case: .flash)
        }
        let views = toItemList(defaultList)
//        let viewWidth = defaultList.count * 50
//        let space = (defaultList.count - 1) * 8
//        let width = viewWidth + space
//        rightStarkView.snp.updateConstraints { make in
//            make.width.equalTo(width)
//        }
        rightStarkView.yp.arrangedSubviews = views
    }

    func removeItem(list: [WmcButtonItemType.HomeNavigation],
                    _case: WmcButtonItemType.HomeNavigation) -> [WmcButtonItemType.HomeNavigation]
    {
        guard list.contains(_case) else { return list }
        var list = list
        var index: Int?
        for (idx, cas) in list.enumerated() {
            if cas == _case {
                index = idx
                break
            }
        }
        guard let index = index else { return list }
        list.remove(at: index)
        return list
    }

    func toItemList(_ caseList: [WmcButtonItemType.HomeNavigation]) -> [UIView] {
        var views: [UIView] = []
        caseList.forEach { cas in
            switch cas {
            case .menu: views.append(menuBtn)
            case .flash: views.append(flashBtn)
            case .feedback: views.append(feedBackBtn)
            case .aspectRatio: views.append(aspectRatioBtn)
            case .filter: views.append(filterBtn)
            case .delay: views.append(delayBtn)
            case .flip: views.append(flipBtn)
            case .cameraSetting: views.append(cameraSettingBtn)
            case .placeholder:
                views.append(UIView())
            case let .custom(view: view):
                views.append(view)
            }
        }
        return views
    }

    /// 刷新闪光灯按钮状态
    func refreshFlashBtnState(_ cameraView: YPGECameraView?) {
        let hashFlash =
            (cameraView?.hasTorch() == true) &&
            (cameraView?.hasFlash() == true)
        reloadLeftItems(hasFlash: hashFlash)
    }

    /// 切换模式
    func switchMode(_ mode: WmcButtonItemType.HomeFunctionMode, cameraView: YPGECameraView?) {
        functionMode = mode
//        refreshFlashBtnState(cameraView)
        // 结束录制
        switchVideoRecordingState(.stop, cameraView: cameraView)
    }

    /// 切换状态
    func switchVideoRecordingState(_ state: WmcHomeVC.VideoRecordState, cameraView: YPGECameraView?) {
        videoRecordState = state
        switch state {
        case .stop:
//            leftStarkView.isHidden = false
            rightStarkView.isHidden = false
        case .being,
             .pause:
//            leftStarkView.isHidden = true
            rightStarkView.isHidden = true
        }
        refreshFlashBtnState(cameraView)
    }
}
